package com.myKng.shareservice.util;

import com.myKng.shareservice.repository.ShareLinkRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.security.SecureRandom;

/**
 * 分享码生成器
 */
@Component
@RequiredArgsConstructor
public class ShareCodeGenerator {

    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int CODE_LENGTH = 8;
    
    private final ShareLinkRepository shareLinkRepository;
    private final SecureRandom random = new SecureRandom();
    
    /**
     * 生成唯一的分享码
     *
     * @return 唯一分享码
     */
    public String generateUniqueCode() {
        String code;
        do {
            code = generateRandomCode();
        } while (shareLinkRepository.findByShareCode(code).isPresent());
        
        return code;
    }
    
    /**
     * 生成随机分享码
     *
     * @return 随机分享码
     */
    private String generateRandomCode() {
        StringBuilder sb = new StringBuilder(CODE_LENGTH);
        for (int i = 0; i < CODE_LENGTH; i++) {
            int randomIndex = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(randomIndex));
        }
        return sb.toString();
    }
}